#### Script to do multiple treeMI imputations for the ready-mix concrete industry
### and export the imputed dataset

#### input files:
####	concrete_gooddata07.csv
####
#### output files:
####	concrete_imputes07.csv

require(tree)


#### read in the "good" dataset, in which we have replaced the Census Bureau imputes/edits with missing values
concrete_gooddata<-read.csv("concrete_gooddata07.csv",header=TRUE)

### Create completed datasets using treeMI:


concrete_imputes<-treeMI(concrete_gooddata,ITER=5,c(0,0,0,0,0,0,1,0,0,0,0),starter=TRUE,PPDdraw = TRUE, minCut = 5,minDev  = 0.000001, startCut = 10, startDev = 0.0001) 

concrete_imputes$impSet$impsetnum <- 1
concrete_imputes$PPDsample$impsetnum <- 1

### For the first imputed dataset, create a new file
write.table(concrete_imputes$impSet,file="concrete_imputes07.csv",append=FALSE,sep=",") 
write.table(concrete_imputes$PPDsample,file="concrete_predicted07.csv",append=FALSE,sep=",") 

for (j in 2:500) {

concrete_imputes<-treeMI(concrete_gooddata,ITER=5,c(0,0,0,0,0,0,1,0,0,0,0),starter=TRUE,PPDdraw = TRUE, minCut = 5,minDev  = 0.000001, startCut = 10, startDev = 0.0001) 

concrete_imputes$impSet$impsetnum <- j
concrete_imputes$PPDsample$impsetnum <- j

### Append the subsequent imputed datasets to the file created for the first dataset

write.table(concrete_imputes$impSet,file="concrete_imputes07.csv",append=TRUE,sep=",",col.names=FALSE) 
write.table(concrete_imputes$PPDsample,file="concrete_predicted07.csv",append=TRUE,sep=",",col.names=FALSE) 

}




